package com.sailorj.itools.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.sailorj.itools.common.Translate;
import com.sailorj.itools.constants.MyState;
import com.sailorj.itools.constants.StorageConfig;
import com.sailorj.itools.gui.ConfigForm;
import org.apache.http.util.TextUtils;


/**
 * Project : TranslatePlugin
 * 2022年10月27日
 */
public class TranslateAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {

        // 获取当前项目对象
        final Project project = event.getProject();
        MyState myState = MyState.getInstance();
        StorageConfig storageConfig = myState.getConfig();
        System.out.println(storageConfig.toString());
        if (TextUtils.isEmpty(storageConfig.getAppId())) {
            // 构建对话框
            DialogBuilder dialogBuilder = new DialogBuilder(project);
            // 创建GUI对象 设置对话框显示内容
            dialogBuilder.setCenterPanel(ConfigForm.getConfigForm());
            dialogBuilder.setTitle("百度翻译开放平台api配置");
            dialogBuilder.setOkOperation(() -> {
                // 置空
                MyState.getInstance().setConfig(new StorageConfig());
                // 再赋值
                storageConfig.setAppId(ConfigForm.getTextFieldApiKey().getText());
                storageConfig.setSecurityKey(ConfigForm.getTextFieldKeyFrom().getText());
                System.out.println(storageConfig.toString());
                if (!TextUtils.isEmpty(storageConfig.getAppId()) && !TextUtils.isEmpty(storageConfig.getSecurityKey())) {
                    myState.setConfig(storageConfig);
                    String translateText = Translate.translateAction(event, "zh");
                    // 关闭对话框
                    dialogBuilder.getDialogWrapper().close(0);
                }
            });
            // 显示对话框
            dialogBuilder.show();
        } else {
            String translateText = Translate.translateAction(event, "zh");
        }
    }

}
